﻿using CommonLib.CacheOperation;
using DispatchingCenter.Dispatch;
using Events.Auth;
using Models.EnumData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using WCFLib.ExceptionExtension;

namespace Businesses.Auth
{
    public class AuthOperation
    {
        public void Auth(Models.Auth.AuthInfo authInfo)
        {
            string[] arrTemp = { AppConfigCache.GetAppSettings("WeChatToken"), authInfo.Timestamp, authInfo.Nonce };

            Array.Sort(arrTemp);
            string originalSignature = string.Join("", arrTemp);

            string encryptedSignature = FormsAuthentication.HashPasswordForStoringInConfigFile(originalSignature, "SHA1");

            if (encryptedSignature.ToLower() != authInfo.Signature.ToLower())
            {
                throw new GException(ErrorCode.ErrorWeChatSignature);
            }
        }

        public string GetOpenIDByOAuthCode(string code)
        {
            var getOAuthAccessInfoEvent = new GetOAuthAccessInfoEvent()
            {
                OAuthCondition = new Models.Auth.OAuthCondition()
                {
                    Code = code
                }
            };

            Dispatcher.ActiveEvent(getOAuthAccessInfoEvent);

            CommonLib.LogOperation.Logger.Info("openid=" + getOAuthAccessInfoEvent.OAuthAccessInfo.OpenID);

            var userInfo = new User.UserOperation().GetUserInfo(new Models.User.UserInfoQueryCondition() { OpenID = getOAuthAccessInfoEvent.OAuthAccessInfo.OpenID });

            new SendMessage.SendCustomerServiceMessageOperation().SendTextMessage(new Models.SendMessage.CustomerServiceTextMessage()
            {
                Content = new Models.Base.BaseTextMessage()
                {
                    Content = "亲爱的用户：" + userInfo.NickName + "，您好，微信功能正在开发中，敬请期待！"
                },
                MessageType = "text",
                ToUser = getOAuthAccessInfoEvent.OAuthAccessInfo.OpenID
            });

            return getOAuthAccessInfoEvent.OAuthAccessInfo.OpenID;
        }
    }
}
